package com.jnu.keepaccounts.record;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jnu.keepaccounts.R;
import com.jnu.keepaccounts.SelectPopWindow;
import com.jnu.keepaccounts.data.DataBank;
import com.jnu.keepaccounts.data.DataTiaoMu;
import com.jnu.keepaccounts.data.DataZhuanZhang;
import com.jnu.keepaccounts.utls.KeyBoardUtils;

import java.util.ArrayList;
import java.util.Calendar;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ZhuanZhangFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ZhuanZhangFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private ShouZhiFragment.FragmentInteraction listener;
    public interface FragmentInteraction{
        void process(DataTiaoMu dataTiaoMu);
    }
    public void onAttach(Activity activity){
        super.onAttach(activity);
        if(activity instanceof ShouZhiFragment.FragmentInteraction){
            listener = (ShouZhiFragment.FragmentInteraction)activity;
        }
    }
    private TextView in;
    private TextView out;
    KeyboardView keyboardView;
    EditText editText;

    private int[] year = new int[1];
    private int[] month = new int[1];
    private int[] day = new int[1];
    public ZhuanZhangFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ZhuanZhangFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ZhuanZhangFragment newInstance(String param1, String param2) {
        ZhuanZhangFragment fragment = new ZhuanZhangFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    ActivityResultLauncher<Intent> launcherSelect = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            if(data == null)return ;
            else {
                int resultcode = data.getIntExtra("resultcode",0);
                String selection = data.getStringExtra("selection");
                switch(resultcode){
                    case 1:in.setText(selection);break;
                    case 2:out.setText(selection);break;
                }
            }
        }
    });

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_zhuan_zhang, container, false);

        editText = view.findViewById(R.id.jine_text);
        //显示自定义软键盘
        keyboardView =  view.findViewById(R.id.keyboardview_1);
        KeyBoardUtils keyBoardUtils = new KeyBoardUtils(keyboardView,editText);
        keyBoardUtils.showKeyboad();


        ConstraintLayout constraintLayout = view.findViewById(R.id.hide);
        constraintLayout.setOnClickListener(v -> {
            keyBoardUtils.hideKeyboard();
        });

        editText.setOnClickListener(v -> {
            keyBoardUtils.showKeyboad();
        });

        Calendar calendar = Calendar.getInstance();
        year[0] = calendar.get(Calendar.YEAR);
        month[0] = calendar.get(Calendar.MONTH)+1;
        day[0] = calendar.get(Calendar.DAY_OF_MONTH);
        in = view.findViewById(R.id.in_text);
        in.setText("现金");
        out = view.findViewById(R.id.out_text);
        out.setText("现金");
        in.setOnClickListener(v -> {
            Intent intent = new Intent(getContext(), SelectPopWindow.class);
            intent.putExtra("requestcode",1);
            launcherSelect.launch(intent);
        });
        out.setOnClickListener(v -> {
            Intent intent = new Intent(getContext(),SelectPopWindow.class);
            intent.putExtra("requestcode",2);
            launcherSelect.launch(intent);
        });

        TextView riqi_text = view.findViewById(R.id.date_text);
        riqi_text.setText(calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DAY_OF_MONTH));

        riqi_text.setOnClickListener(v -> {
            //通过自定义控件AlertDialog实现
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            @SuppressLint("ResourceType") View view1 = (LinearLayout) getLayoutInflater().inflate(R.layout.date, null);
            final DatePicker datePicker = (DatePicker) view1.findViewById(R.id.date_picker);
            //设置日期简略显示 否则详细显示 包括:星期\周
            datePicker.setCalendarViewShown(false);
            //设置date布局
            builder.setView(view1);
            builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //日期格式
                    year[0] = datePicker.getYear();
                    month[0] = datePicker.getMonth()+1;
                    day[0] = datePicker.getDayOfMonth();
                    riqi_text.setText(year[0] +"-"+ month[0] +"-"+ day[0] );
                    dialog.cancel();
                }
            });
            builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.create().show();
        });
        keyBoardUtils.setOnEnsureListener(new KeyBoardUtils.OnEnsureListener() {
            @Override
            public void onEnsure() {
                DataBank dataBank = new DataBank(getContext());
                if(editText.getText()== null);
                else{
                    double ans = jisuan(editText.getText().toString());
                    if(in.getText().toString().equals(out.getText().toString())){

                    }
                    else{
                        DataZhuanZhang dataZhuanZhang = new DataZhuanZhang(3,year[0],month[0],day[0],in.getText().toString(),out.getText().toString(),ans,Calendar.getInstance().getTimeInMillis())   ;
                        ArrayList<DataZhuanZhang> dataZhuanZhangs = dataBank.loadZData();
                        dataZhuanZhangs.add(0,dataZhuanZhang);
                        dataBank.saveZData();
                    }

                }
                listener.process(null);
            }

            @Override
            public void setYuSuan() {

            }
        });
        return view;
    }
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu,v,menuInfo);
    }
    public double jisuan(String s){
        for(int i = 0; i < s.length(); i++)
        {
            if(s.charAt(i) == '*' || s.charAt(i) == '/')
            {
                double num1 = 0, num2 = 0;int len1 = 0, len2 = 0;
                for(int j = i - 1; j >= 0; j--)
                {
                    if(s.charAt(j) == '+' || s.charAt(j) == '-')
                    {
                        String s1 = s.substring(j + 1, i);
                        num1 = Double.parseDouble(s1);
                        len1 = s1.length();
                        break;
                    }
                    if(j == 0)
                    {
                        String s1 = s.substring(j, i);
                        num1 = Double.parseDouble(s1);
                        len1 = s1.length();
                        break;
                    }
                }
                for(int j = i + 1; j < s.length(); j++)
                {
                    if(s.charAt(j) == '+' || s.charAt(j) == '-' || s.charAt(j) == '*' || s.charAt(j) == '/' )
                    {
                        String s1 = s.substring(i + 1, j);

                        num2 = Double.parseDouble(s1);
                        len2 = s1.length();
                        break;
                    }
                    if(j == s.length() - 1)
                    {
                        String s1 = s.substring(i + 1, j+1);
                        num2 = Double.parseDouble(s1);
                        len2 = s1.length();
                        break;
                    }
                }
                if(s.charAt(i) == '*')
                {
                    double res = num1 * num2;
                    String s2 = s.substring(i - len1, i +len2 + 1);
                    String s3 = res + "";
                    s = s.replace(s2, s3);
                    i = i - len1 - 1 + s3.length();
                    continue;
                }
                if(s.charAt(i) == '/')
                {
                    double res = num1 / num2;
                    String s2 = s.substring(i - len1, i +len2 + 1);
                    String s3 = res + "";
                    s = s.replace(s2, s3);
                    i = i - len1 - 1 + s3.length();
                    continue;
                }

            }
        }

        //加减计算
        for(int i = 0; i < s.length(); i++)
        {
            if(s.charAt(i) == '+' || s.charAt(i) == '-')
            {
                double num1 = 0, num2 = 0;int len1 = 0, len2 = 0;
                for(int j = i - 1; j >= 0; j--)
                {
                    if(j == 0)
                    {
                        String s1 = s.substring(j, i);
                        num1 = Double.parseDouble(s1);
                        len1 = s1.length();
                        break;
                    }
                }
                for(int j = i + 1; j < s.length(); j++)
                {
                    if(s.charAt(j) == '+' || s.charAt(j) == '-')
                    {
                        String s1 = s.substring(i + 1, j);
                        num2 = Double.parseDouble(s1);
                        len2 = s1.length();
                        break;
                    }
                    if(j == s.length() - 1)
                    {
                        String s1 = s.substring(i + 1, j+1);
                        num2 = Double.parseDouble(s1);
                        len2 = s1.length();
                        break;
                    }
                }
                if(s.charAt(i) == '+')
                {
                    double res = num1 + num2;
                    String s2 = s.substring(i - len1, i +len2 + 1);
                    String s3 = res + "";
                    s = s.replace(s2, s3);
                    i = i - len1 - 1 + s3.length();
                    continue;
                }
                if(s.charAt(i) == '-')
                {
                    double res = num1 - num2;
                    String s2 = s.substring(i - len1, i +len2 + 1);
                    String s3 = res + "";
                    s = s.replace(s2, s3);
                    i = i - len1 - 1 + s3.length();
                    continue;
                }
            }
        }
        return Double.parseDouble(s);
    }
    public void onDetach(){
        super.onDetach();
        listener = null;
    }
}